<template>
    <div class="client-nursing-container">
        <h2 class="title">客户总览</h2>

        <!-- 查询表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
            <div class="search-left">
                <el-form-item label="客户名:">
                    <el-input v-model="searchForm.name" placeholder="请输入客户名" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="goToConfig">前往配置健康管家</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="warning" @click="exportExcel">导出 Excel</el-button>
                </el-form-item>

            </div>

        </el-form>

        <!-- 客户信息表格 -->
        <el-table :data="tableData" v-loading="loading" border style="width: 100%; background: #f5f7fa;"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column prop="name" label="客户名" />
            <el-table-column prop="gender" label="性别" width="80" />
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="phone" label="电话" />
            <el-table-column prop="familyContact" label="家属联系方式" />
            <el-table-column prop="idNumber" label="身份证号" />
            <el-table-column prop="bloodType" label="血型" width="100" />
            <el-table-column prop="caretakerName" label="护工姓名" />
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="success" size="small" style="margin-left: 8px"
                        @click="openEdit(scope.row)">修改信息</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-bar">
            <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size"
                :total="pagination.total" :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper"
                @current-change="handleCurrentChange" @size-change="handleSizeChange" />
        </div>

        <EditClientDialog ref="editRef" @success="query(pagination.cur)" />
    </div>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import { inject } from 'vue'
const axios = inject("axios")
import { ElMessage } from 'element-plus'
import EditClientDialog from '@/components/EditClientDialog.vue'
import router from '@/router'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'


const searchForm = ref({ name: '' })
const tableData = ref([])
const loading = ref(false)
const pagination = ref({ cur: 1, size: 5, total: 0 })

const editRef = ref()

const openEdit = (row) => {
    editRef.value.open(row)
}

const handleSearch = () => {
    pagination.value.cur = 1
    query(1)
}

const handleReset = () => {
    searchForm.value.name = ''
    pagination.value.cur = 1
    query(1)
}

const query = async (page) => {
    loading.value = true
    try {
        // 请求数据，调用新的接口
        const res = await axios.get('/client/pageClientAndCaretaker', {
            params: {
                cur: page,
                number: pagination.value.size,
                name: searchForm.value.name // 根据客户名搜索
            }
        })
        // 判断接口返回状态
        if (res.data.status === 200) {
            const rawData = res.data.data || []

            // 处理数据：提取 client 信息并加入护工姓名
            tableData.value = rawData.map(item => {
                return {
                    ...item.client,  // 客户信息
                    caretakerName: item.user?.username || '无' // 护工姓名，若为空则显示'无'
                }
            })

            // 更新分页信息
            pagination.value.total = res.data.total || 0
        } else {
            // 如果接口返回失败，弹出警告
            ElMessage.warning(res.data.msg || '查询失败')
        }
    } catch (err) {
        // 处理请求出错情况
        ElMessage.error('查询失败：' + err.message)
    } finally {
        loading.value = false
    }
}


const handleCurrentChange = (page) => {
    pagination.value.cur = page
    query(page)
}

const handleSizeChange = (size) => {
    pagination.value.size = size
    pagination.value.cur = 1
    query(1)
}

onMounted(() => {
    query(1)
})

const open = (clientId) => {
    visible.value = true
    loadDataByClientId(clientId)
}

defineExpose({ open })

const goToConfig = () => {
    // 跳转到健康管家配置页面
    router.push("/homeView/nursingManage/clientNursingTable")
}

const exportExcel = async () => {
  loading.value = true
  try {
    const res = await axios.get('/client/pageClientAndCaretaker', {
      params: {
        cur: 1,
        number: 1000, // 一次加载全部数据
        name: searchForm.value.name
      }
    })
    if (res.data.status === 200) {
      const rawData = res.data.data || []

      // 整理导出数据
      const exportData = rawData.map(item => {
        return {
          客户名: item.client?.name || '',
          性别: item.client?.gender || '',
          年龄: item.client?.age || '',
          电话: item.client?.phone || '',
          家属联系方式: item.client?.familyContact || '',
          身份证号: item.client?.idNumber || '',
          血型: item.client?.bloodType || '',
          护工姓名: item.user?.username || '无'
        }
      })

      // 创建工作表和工作簿
      const worksheet = XLSX.utils.json_to_sheet(exportData)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, '客户信息')

      // 导出文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
      saveAs(blob, '客户信息.xlsx')
    } else {
      ElMessage.warning(res.data.msg || '导出失败')
    }
  } catch (err) {
    ElMessage.error('导出失败：' + err.message)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.client-nursing-container {
    padding: 20px;
}

.title {
    font-size: 27.2px;
    font-weight: bold;
    margin: 0 0 20px 0;
    color: #333;
}

.search-form {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    margin-bottom: 20px;
}

.search-left {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.pagination-bar {
    display: flex;
    justify-content: flex-end;
    margin-top: 2%;
    margin-bottom: 2%;
}
</style>
